import asyncio
from playwright.async_api import async_playwright


async def convert_webpage_to_pdf(url, output_path):
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        page = await context.new_page()

        await page.set_viewport_size({"width": 1920, "height": 1080})
        await page.goto(url)

        # 注入CSS防止内容分页
        await page.add_style_tag(content="""
            body {
                width: 100% !important;
                overflow: visible !important;
                page-break-before: avoid !important;
                page-break-after: avoid !important;
                page-break-inside: avoid !important;
            }
            * {
                break-inside: avoid !important;
                break-before: avoid !important;
                break-after: avoid !important;
            }
        """)

        # 获取页面完整高度
        total_height = await page.evaluate("() => document.body.scrollHeight")

        # 生成PDF（超大单页）
        await page.pdf(
            path=output_path,
            width="1200px",
            height=f"{total_height + 100}px",  # 增加余量
            margin={"top": "0", "right": "0", "bottom": "0", "left": "0"},
            print_background=True,
            page_ranges="1"  # 强制只输出一页
        )

        await browser.close()


if __name__ == "__main__":
    import sys

    if len(sys.argv) != 3:
        print("用法: python webpage_to_pdf.py <URL> <输出PDF路径>")
        sys.exit(1)

    url = sys.argv[1]
    output_path = sys.argv[2]
    asyncio.run(convert_webpage_to_pdf(url, output_path))